package com.easylinkin.linkappapi.common.exceptions;

import com.easylinkin.linkappapi.common.utils.MessageUtils;
import com.easylinkin.linkappapi.openapi.common.CommonResult;
import java.util.IllegalFormatException;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import site.morn.rest.RestBuilders;

/**
 * <p></p>
 *
 * @author TongJie
 * @since 2020/4/11 12:54
 */

@ControllerAdvice(basePackages = {"com.easylinkin"})
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public Object businessExceptionHandler(HttpServletRequest req, BusinessException e) {
        LOGGER.error("发生业务异常！code及原因是", e);
        if (req.getRequestURI() != null && req.getRequestURI().indexOf("/openApi/") != -1) {
            return CommonResult.failed(e);
        }
        return RestBuilders.failureBuilder().code(e.getErrorCode()).message(MessageUtils.get(e.getMessage())).build();
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object exceptionHandler(HttpServletRequest req, Exception e) {
        LOGGER.error("系统异常：", e);
        String message;
        String data = "错误详细信息信息: e.message信息:" + e.getMessage() + ",e.toString()信息:" + e.toString();
        if (e instanceof NullPointerException) {
            message = "空指针异常";
        } else if (e instanceof IllegalFormatException) {
            message = "参数不合法";
        } else if (e instanceof HttpMessageNotReadableException) {
            message = "参数格式错误";
        } else if (e instanceof IllegalArgumentException){ //业务异常 参数异常
            return RestBuilders.failureBuilder().data(data).message(MessageUtils.get(e.getMessage())).build();
        } else {
            message = e.getMessage();
        }
        if (req.getRequestURI() != null && req.getRequestURI().indexOf("/openApi/") != -1) {
            return CommonResult.failed(e).setMessage(message).setData(data);
        }
        return RestBuilders.errorBuilder().code("exception").data(data).message(message).build();
    }
}
